package com.dishi.hj212.service.impl;


import com.alibaba.fastjson2.JSON;
import com.dishi.hj212.core.DataAreaParser;
import com.dishi.hj212.domain.StWaterqualityR;
import com.dishi.hj212.mapper.StWaterqualityRMapper;
import com.dishi.hj212.model.DataArea;
import com.dishi.hj212.model.DataSegment;
import com.dishi.hj212.service.IStWaterqualityRService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 水质自动监测数据Service业务层处理
 *
 * @author dishi
 * @date 2023-11-29
 */
@RequiredArgsConstructor
@Service(value = "stWaterqualityRService")
public class StWaterqualityRServiceImpl implements IStWaterqualityRService {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); // 定义日期格式
    @Resource
    private StWaterqualityRMapper stWaterqualityRMapper;

    @Override
    public Boolean saveStWaterqualityData(DataSegment dataSegment) throws Exception {
        String cp = dataSegment.getCp();
        DataAreaParser dataAreaParser = new DataAreaParser();
        Map<String, String> dataAreaMap = dataAreaParser.readDataAreaMap(cp);
//        JSONObject jsonObject = (JSONObject) JSON.toJSON(dataAreaMap);
        Map<String, String> map = mergeDataAreaMap(dataAreaMap);
        DataArea dataArea = JSON.parseObject(JSON.toJSONString(map), DataArea.class);
        StWaterqualityR stWaterqualityR = new StWaterqualityR();
        BeanUtils.copyProperties(dataArea, stWaterqualityR);
//        JSONObject json = (JSONObject) JSON.toJSON(dataArea);
        stWaterqualityR.setStcd(dataSegment.getMn());
        String timeStr = dataAreaMap.get("DataTime");
        Date now = StringUtils.isNotBlank(timeStr) ? sdf.parse(timeStr) : new Date();
        stWaterqualityR.setSpt(now);
        return this.stWaterqualityRMapper.insert(stWaterqualityR) > 0 ? true : false;
    }


    /**
     * 把后缀 -Rtd 去除
     */
    private Map<String, String> mergeDataAreaMap(Map<String, String> dataAreaMap) {
        Iterator<String> iterator = dataAreaMap.keySet().iterator();
        Map<String, String> mergeDataAreaMap = new HashMap<>();
        while (iterator.hasNext()) {
            String key = iterator.next();
            if (key.contains("-Rtd")) {
                String value = dataAreaMap.get(key);
                mergeDataAreaMap.put(key.replace("-Rtd", ""), value);
//                iterator.put(key.replace("-Rtd", ""), value);
                iterator.remove();

            }
        }

        return mergeDataAreaMap;
    }
}
